package com.KegController.BrewCoder;

import com.KegController.BrewCoder.adkService.adkBinder;

import com.android.future.usb.UsbManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;

import android.content.SharedPreferences;

import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;

import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class KegControllerActivity extends Activity implements OnClickListener {

	private static final String TAG = "KegControllerActivity";
	private static final String adkServiceMessage = "BrewCoder.KegController.ServiceMessage";
	static final int DIALOG_TEMP_LIST_ID = 0;

	SharedPreferences preferences;
	AlertDialog tempListSelect;

	TextView currentTempReadout;
	EditText currentSetTempReadout;
	EditText pulseRate;
	EditText autoPressure;
	RadioButton compressorON;
	RadioButton lightON;
	ToggleButton autoPressureEnable;

	Button sendCANmessage;
	Button pwmButtonPlus;
	Button pwmButtonMinus;
	Button pulseCO2;

	private boolean activityBound = false;

	adkService mADKservice;


	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "ONRESUME");
		
		if(activityBound){
		mADKservice.updateCelsius();
		currentSetTempReadout.setText(mADKservice.getCurrentSetTempFormatted());
		adkDataMessageUpdate();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "ONPAUSE");

	}

	@Override
	public void onDestroy() {
		Log.d(TAG, "onDestroy");
		unregisterReceiver(myReceiver);
		// Update Binding stuff!!!
		// if (activityBound)
		// unbindService(mADKserviceConnection);

		super.onDestroy();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	//	setContentView(R.layout.main);


		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		
		// **************** Start to setup ADK stuff ********************
		IntentFilter filter = new IntentFilter(
				UsbManager.ACTION_USB_ACCESSORY_DETACHED);

		filter.addAction(adkServiceMessage);
		filter.addAction(mADKservice.adkServiceShuttingDown);
		registerReceiver(myReceiver, filter);

		
		
		// Update UI
		hideControls();
	} // end onCreate

	public void bindWithAdkService(boolean state) {
		if (state) {
			// Bind to LocalService
			Intent intent = new Intent(this, adkService.class);
			bindService(intent, mADKserviceConnection, Context.BIND_AUTO_CREATE);
		} else{
			if(activityBound){
			activityBound = false;
			hideControls();
			unbindService(mADKserviceConnection);
		//	adkDataMessageUpdate();
			}
		}
	}

	// Setup button click's
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.bSendUSB:
				if (activityBound) {
				mADKservice
						.setCurrentSetTemp(Long.parseLong(currentSetTempReadout
								.getText().toString()) * 100);
				mADKservice.sendCommand(2,
						(int) mADKservice.getCurrentSetTemp());
			}
			break;

		case R.id.bMinus:
			if (activityBound)
				mADKservice.sendCommand(3, 0);
			break;

		case R.id.bPlus:
			if (activityBound)
				mADKservice.sendCommand(3, 1);
		break;
		case R.id.bPulse:
			if (activityBound) {
				mADKservice.sendCommand(4,Integer.parseInt(pulseRate.getText().toString()));				
			}
				break;
		}
	}

	// Intent broadcast receiver for Service broadcast and ask attachment
	private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
	//		Log.d(TAG, "myReceiver action: " + action);

			if (adkServiceMessage.equals(action)) {
				if (!activityBound)
					bindWithAdkService(true);
					adkDataMessageUpdate();
			}
			if (adkService.adkServiceShuttingDown.equals(action)) {
				Log.d(TAG, "unbind!!");
				bindWithAdkService(false);
				
				
			}
		}
	};

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater popUp = getMenuInflater();
		popUp.inflate(R.menu.main_menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exitApp:
			if (activityBound) {
				bindWithAdkService(false);
				// if (!mADKservice.adkIsconnected()) {
				Intent intent = new Intent(this, adkService.class);
				stopService(intent);
			}
			// mADKservice.stopADKservice();
			KegControllerActivity.this.finish();
			break;
		case R.id.preferences:
			Intent i = new Intent(KegControllerActivity.this,
					MyPreferencesActivity.class);
			startActivity(i);
			break;
		}
		return true;
	}

	String[] getTempArry() {
		String[] arr = new String[30]; // = {"0.0"};
		double count = 0;
		// arr[0] = String.valueOf(0);
		for (int x = 0; x < arr.length; x++) {
			arr[x] = String.valueOf(count += .5);
		}
		return arr;
	}

	/** Defines callbacks for service binding, passed to bindService() */
	private ServiceConnection mADKserviceConnection = new ServiceConnection() {

		// @Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			adkBinder binder = (adkBinder) service;
			mADKservice = binder.getService();
			activityBound = true;
			showControls();
		}


		public void onServiceDisconnected(ComponentName arg0) {
			
		}
		
	};

	private void adkDataMessageUpdate() {
		if (activityBound) {
			// mADKservice.setCelsius();
			currentTempReadout.setText(mADKservice
					.getCurrentInteriorTempFormatted());
			Log.d(TAG, "update display NOW!!!");
			// compressorON.setChecked(mADKservice.isCompressorON());
			// lightON.setChecked(mADKservice.isLightON());
			

		}
/*		else {
			
			currentTempReadout.setText("No ADK");
			compressorON.setChecked(false);
			lightON.setChecked(false);
		}*/
	}
	void showControls(){
		setContentView(R.layout.main);
		
		sendCANmessage = (Button) findViewById(R.id.bSendUSB);
		pwmButtonMinus = (Button) findViewById(R.id.bMinus);
		pwmButtonPlus = (Button) findViewById(R.id.bPlus);
		pulseCO2 = (Button) findViewById(R.id.bPulse);
		autoPressureEnable = (ToggleButton) findViewById(R.id.togbAutoPressure);
		
		compressorON = (RadioButton) findViewById(R.id.rbCompressorON);
		lightON = (RadioButton) findViewById(R.id.rbLightsON);

		currentTempReadout = (TextView) findViewById(R.id.tvCurrentTemp);
		currentSetTempReadout = (EditText) findViewById(R.id.tvSetTemp);
		pulseRate = (EditText) findViewById(R.id.etPulseRate);
		autoPressure = (EditText)findViewById(R.id.etAutoPressure);
		
		
		pulseRate.setText("500");
		pwmButtonMinus.setOnClickListener(this);
		pwmButtonPlus.setOnClickListener(this);
		sendCANmessage.setOnClickListener(this);
		pulseCO2.setOnClickListener(this);
		
		autoPressureEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
		    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		        if (isChecked) {
		        	int x = Integer.parseInt(autoPressure.getText().toString());
		        	if(x < 0)
		        		x = 0;		
		        	mADKservice.sendCommand(5,x);
							
		        } else {
		        	mADKservice.sendCommand(5,-1);
		        }
		    }
		});
		/*gasToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
		    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		        if (isChecked) {
		        	mADKservice.sendCommand(4,1);
							
		        } else {
		        	mADKservice.sendCommand(4,0);
		        }
		    }
		});
		*/
		currentSetTempReadout.setText(mADKservice.getCurrentSetTempFormatted());
	}

	
	
	void hideControls(){

		setContentView(R.layout.no_adk);
		if(currentSetTempReadout != null){
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(currentSetTempReadout.getWindowToken(), 0);
		}
		


	}
}